import json
import os
import re

r_opr_name = re.compile(r'(.*).txt')
r_name = re.compile(r'name = (.*)')


def handle_plot():
    # class OperaPlot(db.Model):
    #     opr_name = db.Column(db.String(50), db.ForeignKey('opera.opr_name'), primary_key=True)
    #     name = db.Column(db.String(50), primary_key=True)
    #     plot = db.Column(db.Text)
    # 扫描目录
    obj = 'plot'
    cla = 'OperaPlot'
    my_dir = './' + obj + '/'
    file_list = os.listdir(my_dir)
    out = open('./plot-script.txt', mode='w', encoding='utf-8')
    for f in file_list:
        fin = open(my_dir + f, mode='r', encoding='utf-8')
        obj = {'opr_name': r_opr_name.findall(f)[0]}
        plot = []
        first = True
        while True:
            fread = fin.readline()
            if not fread:
                break
            print(fread)
            name_list = r_name.findall(fread)
            if len(name_list) > 0:
                if not first:
                    obj['plot'] = json.dumps(plot)
                    plot = []
                    res_str = "db.session.add(" + cla + "(opr_name='"
                    res_str += obj['opr_name'] + "', name='" + obj['name'] + "', plot='''"
                    res_str += obj['plot'] + "'''))\n"
                    print(res_str)
                    out.write(res_str)
                else:
                    first = False
                obj['name'] = name_list[0]
            else:
                plot.append(fread.strip('\n'))
        obj['plot'] = json.dumps(plot)
        res_str = "db.session.add(" + cla + "(opr_name='"
        res_str += obj['opr_name'] + "', name='" + obj['name'] + "', plot='''"
        res_str += obj['plot'] + "'''))\n"
        print(res_str)
        out.write(res_str)
    out.write("db.session.commit()\n")
    out.close()


if __name__ == "__main__":
    handle_plot()
    pass
